package com.zhuiyun.project.security.commonhandler;

import com.zhuiyun.project.api.system.user.entity.SysUser;
import com.zhuiyun.project.api.system.user.service.SysUserService;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.common.response.ResponseUtil;
import com.zhuiyun.project.security.jwt.JWTConfig;
import com.zhuiyun.project.security.jwt.JWTUtils;
import com.zhuiyun.project.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * @ClassName AuthenticationSuccessHandler
 * @Description 登录成功的操作
 * @Author zcy
 * @Date 2023/3/27 11:20
 **/
@Component
public class UserLoginAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    SysUserService sysUserService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        SysUser sysUser = (SysUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        sysUser.setLastLoginTime(new Date());
        sysUser.setUpdateTime(new Date());
        // 获取登录ip
        sysUser.setLastLoginIp(request.getLocalAddr());
        sysUserService.updateUserByLogin(sysUser);
        String token = JWTUtils.createAccessToken(sysUser);
        // 设置token过期时间
        RedisUtil.set(token,sysUser,JWTConfig.expiration);
        RedisUtil.set(sysUser.getLoginName(),token,JWTConfig.expiration);
        token = JWTConfig.tokenPrefix + token;
        // 将token 放入redis中
        ResponseUtil.responseJson(response, CommonResult.ok(token));
    }
}
